<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 迭代器 iterator(遍历器)，方便来遍历对象，for..of
        const it = {
            _data: [1,2,3],
            _index: 0,//索引值
            next(){
                return this._index < this._data.length?{
                    value: this._data[this._index++],
                    done: false//未完成
                }:{
                    value: undefined,
                    done: true
                }
            }
        }

        console.log(it.next());//{value:1 done:false}
        console.log(it.next());//{value:2 done:false}
        console.log(it.next());//{value:3 done:false}
        console.log(it.next());//{value:undefined done:true}


        // 迭代器方法/函数
        // 闭包，_index与data都是闭包变量
        function makeIterator(data){
            let _index = 0;
            return{
                next(){
                    return _index < data.length?
                    {
                        value: data[_index++],
                        done: false//未完成
                    }:{
                        value: undefined,
                        done: true
                }
            }
        }
    }

    const it1 = makeIterator(["hello","iterator"]);
    console.log(it1.next());
    console.log(it1.next());
    console.log(it1.next());

    
    </script>
</body>
</html>